#include "stdafx.h"
#include "DataHost.h"


DataHost::DataHost()
:m_theEmptyWork(m_theIoSvc),
m_theAcceptor(m_theIoSvc)
{

	for (int i=0; i<num_session_mgrs; i++)
	{
		m_theSesMgrs[i] = NULL;
	}
}

DataHost::~DataHost()
{

}

bool
DataHost::start()
{
	for (int i=0; i<num_session_mgrs; i++)
	{
		if (m_theSesMgrs[i] == NULL)
		{
			m_theSesMgrs[i] = new DataSessionMgr(m_theIoSvc);
		}
	} 

	m_theEndPoint.port(4000);

	m_theAcceptor.open(boost::asio::ip::tcp::v4());

	m_theAcceptor.bind(m_theEndPoint);

	m_theAcceptor.listen();

	for (int i=0; i< num_working_thread; i++)
	{
		m_theThreads[i] = boost::thread(boost::bind(&boost::asio::io_service::run, &m_theIoSvc));
	}

	return true;
}

bool
DataHost::stop()
{
	return true;
}

bool
DataHost::wait()
{
	for (int i=0; i< num_working_thread; i++)
	{
		m_theThreads[i].join();
	}
	return true;
}

bool 
DataHost::createSession(DataSession*& pSession)
{
	return true;
}

bool
DataHost::releaseSession(DataSession* pSession)
{
	return true;
}



void 
DataHost::onSessionStart(DataSession* pSes, const boost::system::error_code& error)
{
	if (pSes!=NULL && !error)
	{
		pSes->read();
		pSes->read();
	}

	post_accept();
}

void
DataHost::onSessionEnd(DataSession* pSes)
{
	if (pSes)
	{
		createSession(pSes);
	}
}



void
DataHost::post_accept()
{
	DataSession* pNewSes =  NULL;
	if (releaseSession(pNewSes))
	{
		m_theAcceptor.async_accept(pNewSes->getSocket(),
			boost::bind(&DataHost::onSessionStart, this, pNewSes, boost::asio::placeholders::error));
	}
}